package com.xyxy.platform.modules.core.web.response;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.io.Serializable;
import java.util.List;

/**
 * 系统标准的响应输出类
 * User: VirtueCai
 * Date: 15-11-20
 * Time: 下午11:43
 */
public class ResponseMessage<T> implements Serializable {
    private boolean success;
    private boolean hasErrors;
    private String message;
    private Integer code;
    private long timeSpan;
    private T result;

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public void setResult(T result) {
        this.result = result;
    }

    public void setTimeSpan(long timeSpan) {
        this.timeSpan = timeSpan;
    }

    public void setHasErrors(boolean hasErrors) {
        this.hasErrors = hasErrors;
    }

    public boolean isSuccess() {
        return success;
    }

    public String getMessage() {
        return message;
    }

    public Integer getCode() {
        return code;
    }

    public T getResult() {
        return result;
    }

    public long getTimeSpan() {
        return timeSpan;
    }

    public boolean isHasErrors() {
        return hasErrors;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    /**
     * 从JSON字符串转换为响应对象
     * 响应结果为列表
     *
     * @param response 响应JSON字符串
     * @param clazz    响应对象
     * @param <T1>     对象类型
     * @return 响应对象
     */
    public static <T1> ResponseMessage<List<T1>> fromToListResult(String response, Class<T1> clazz) {
        ResponseMessage<List<T1>> rst = JSON.parseObject(response, new TypeReference<ResponseMessage<List<T1>>>() {
        });
        return rst;
    }

    /**
     * 响应结果为对象
     *
     * @param response 响应JSON
     * @param clazz    结果对象
     * @param <T1>     结果
     * @return 响应对对象
     */
    public static <T1> ResponseMessage<T1> from(String response, Class<T1> clazz) {
        ResponseMessage<T1> rst = JSON.parseObject(response, new TypeReference<ResponseMessage<T1>>() {
        });
        return rst;
    }
}